package com.hzw.saas.service.rbac.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.hzw.saas.api.rbac.bo.PermissionBO;
import com.hzw.saas.api.rbac.bo.PermissionTreeBO;
import com.hzw.saas.api.rbac.enums.PermSysEnum;
import com.hzw.saas.api.rbac.enums.PermTypeEnum;
import lombok.experimental.UtilityClass;

/**
 * @author zzl
 * @since 08/31/2021
 */
@UtilityClass
public class RbacUtil {

    public static void assemblePermissionText(PermissionBO bo) {
        if (Objects.isNull(bo))
            return;
        bo.setSysText(PermSysEnum.getText(bo.getSys()));
        bo.setTypeText(PermTypeEnum.getText(bo.getType()));
    }

    public static void assemblePermissionText(List<? extends PermissionBO> bos) {
        if (Objects.isNull(bos))
            return;
        bos.forEach(RbacUtil::assemblePermissionText);
    }

    public static List<PermissionTreeBO> assemblePermissionTrees(List<PermissionTreeBO> sources, String supId, Integer level) {
        if (Objects.isNull(level))
            level = -1;
        if (level == 0) {
            return new ArrayList<>();
        }
        List<PermissionTreeBO> permissions = sources.stream().filter(permission -> Objects.equals(supId, permission.getSupId()))
            .collect(Collectors.toList());
        if (--level == 0) {
            return permissions;
        }
        for (PermissionTreeBO permission : permissions) {
            List<PermissionTreeBO> subPermissions = assemblePermissionTrees(sources, permission.getPid(), level);
            permission.setChildren(subPermissions);
        }
        return permissions;
    }

    public static List<String> listAllPids(List<PermissionTreeBO> permTrees) {
        List<String> pids = new ArrayList<>();
        for (PermissionTreeBO permTree : permTrees) {
            pids.add(permTree.getPid());
            if (Objects.nonNull(permTree.getChildren())) {
                pids.addAll(listAllPids(permTree.getChildren()));
            }
        }
        return pids;
    }

}
